<template>
  <div class="order-detail-page">
    <div>
      <cp-nav-bar v-if="type == '0'" title="待付款" />
      <cp-nav-bar v-if="type == '1'" title="待使用" />
      <cp-nav-bar v-if="type == '2'" title="已完成" />
      <cp-nav-bar v-if="type == '3' && (item?.payState !== 4 || item?.payState !== 5)" title="申请退款" />
      <cp-nav-bar v-if="type == '3' && item?.payState == 5" title="退款中" />
      <cp-nav-bar v-if="type == '3' && (item?.payState == 4 || item?.payState == 3)" title="退款详情" />
      <cp-nav-bar v-if="type == '4'" title="已取消" />
    </div>
    <div style="flex: 1;">
      <div class="countdown" v-if="type === '0'">
        <p>待付款，剩余 <span> {{ minutes < 10 ? '0' + minutes : minutes }}:{{ seconds < 10 ? '0' + seconds : seconds }}</span>
        </p>
        <p>超过30分钟未支付，订单将自动取消</p>
      </div>
      <div class="refundStatus" v-if="type === '3' && item?.payState == 5">
        <p class="refundStatus-title">退款中</p>
        <div class="schedule">
          <p><span>请等待商家处理</span><span><i>￥</i>{{ item?.actualAmount
          }}</span></p>
          <p>你已发起退款申请，请耐心等待商家处理</p>
        </div>
      </div>
      <div class="refundStatus" v-if="type === '3' && item?.payState == 4">
        <p class="refundStatus-title">退款完成</p>
        <div class="schedule">
          <p>已原路退回</p>
        </div>
      </div>
      <div class="refundStatus" v-if="type === '3' && item?.payState == 3">
        <p class="refundStatus-title">退款失败</p>
        <div class="schedule" v-if="item.errMsg">
          <p>{{ item.errMsg }}</p>
        </div>
      </div>
      <div class="orderInfo">
        <img :src="baseURL + item?.fileList[0].filePath" alt="">
        <div class="orderInfo-content">
          <p style="font-size: 14px;font-weight: 700;margin-bottom: 10px;">{{ item?.ticketName }}</p>
          <p style="margin-bottom: 15px;">
            <span style="margin-right: 5px;" v-for="items in item?.scenicLabel.split(',')" :key="items">
              {{ scenic_label_type[items]?.label }}
            </span>
          </p>
          <p class="price"><i>￥</i>{{ item?.orderAmount }}</p>
        </div>
      </div>
      <div class="orderInfoCard" v-if="type === '0' || type === '1' || type === '4' || type === '2'">
        <div class="quick">
          <div v-if="type === '1' || type === '2'">
            <p class="quickTitle">快速验券</p>
            <img :src="item?.qrCodeUrl" alt="" @click="showQrCode(item?.qrCodeUrl)">
            <div class="ticketCode">
              <span style="color: #878787;">券码</span>{{ item?.orderECode }}
              <span style="color: #2a82e4;" v-clipboard="item?.orderECode" v-clipboard:success="copy">复制</span>

            </div>
          </div>
          <p>订单信息</p>
          <p><span>订单金额</span><span><i>￥</i>{{ item.orderAmount }}</span></p>
          <p v-if="item?.discountAmount"><span>商品优惠</span><span style="color: #CB161D;"><i>￥</i>-{{ item?.discountAmount
          }}</span></p>
          <p><span>实际金额</span><span style="color: #CB161D;"><i>￥</i>{{ item?.actualAmount }}</span></p>
          <div class="orderTime">
            <p><span>订单编号：</span>
              <span>
                <span style="color: #2a82e4;" v-clipboard="item?.orderId" v-clipboard:success="copy">复制</span>
                {{ item?.orderId }}
              </span>
            </p>
            <p><span>下单时间：</span><span>{{ item?.createTime }}</span></p>
            <p v-if="type === '1' || type === '2'"><span>付款时间:</span><span>{{ item?.payTime }}</span></p>
            <p v-if="type === '1' || type === '2'"><span>支付方式：</span><span>{{ item?.payType == '0' ? '微信' : item?.payType
              == '1' ? '支付宝' : item?.payType == '4' ? '银联' : item?.payType == '6' ? '数字人民币' : '其他' }}</span></p>
          </div>
        </div>
      </div>
      <div class="requestRefund" v-if="type == '3' && item?.payState == 1">
        <p>
          <van-field v-model="queryparams.refundReason" is-link readonly name="refundReason" input-align="right"
            label="退款原因" placeholder="请选择" @click="showPicker = true" />
        </p>
        <p>
          <span>退款金额</span><span><i style="font-size: 12px; font-style: normal;">￥</i>{{ item?.actualAmount }}</span>
        </p>
        <p style="margin-top: 0; color: #878787">实际退款金额以到账金额为准</p>
        <p><span>退款方式</span><span>原路退回</span></p>
      </div>
      <div class="refundDetail" v-if="type == '3' && (item?.payState == 4 || item?.payState == 3)">
        <p><span>订单编号</span><span>
            <span style="color: #2a82e4;" v-clipboard="item.orderId" v-clipboard:success="copy">复制</span>
            {{ item.orderId }}</span>
        </p>
        <p><span>退款时间</span><span>{{ item.refundTime }}</span></p>
        <!-- <p> -->
        <p><span>退款金额</span><span><i style="font-size: 12px; font-style: normal;">￥</i>{{ item?.actualAmount }}</span>
        </p>
        <p style="margin-top: 0; color: #878787">实际退款金额以到账金额为准</p>
        <!-- </p> -->
        <p><span>退款方式</span><span>原路退回</span></p>
        <p><span>退款原因</span><span>{{ refund_reason[item?.refundReason]?.label }}</span></p>
      </div>
    </div>
    <div class="order-detail-foot">
      <div class="footInfo">
        <p v-if="type == '3' && item?.payState == 1">
          <i>￥</i>
          <span class="price">{{ item.actualAmount }}</span>
          <span class="firstPrice" v-if="item?.discountAmount">
            <i>￥</i>{{ item.orderAmount }}
          </span>
        </p>
        <p v-if="type == '3' && item?.payState == 1 && item?.discountAmount"
          style="color: var(--cp-primary);margin-top:2px;">
          优惠{{ item.discountAmount }}元
          <!-- <span style="color:rgba(166, 166, 166, 1);margin-right: 30px;">明细</span> -->
          <!-- <van-icon name="play" style="transform: rotate(-90deg);color:rgba(166, 166, 166, 1) " /> -->
        </p>
        <span class="greybtn" v-if="type == '0'" @click="getcancelOrder(item)">取消订单</span>
        <span class="greybtn" @click="getRefund" v-if="type == '1'">申请退款</span>
        <span class="greybtn" v-if="type == '4'" @click="getdeleteOrder(item)">删除订单</span>
      </div>
      <div>
        <span class="confirmbtn" @click="getRefundOrder(item)" v-if="type == '3' && item?.payState == 1">提交订单</span>
        <span class="confirmbtn" @click="getagainOrder(item)"
          v-if="type == '1' || type == '2' || type == '4' || item?.payState == 4">再来一单</span>
        <span class="confirmbtn" v-if="type == '0'" @click="pay(item)">去付款</span>
      </div>
    </div>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker :columns="refund_reason" :columns-field-names="customFieldName" @confirm="onConfirm"
        @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>
<script setup lang="ts">


import { getOrderById, cancelOrder, delOrder, getpreOrder, refundOrder } from '@/services/home'
import { ref, computed, onBeforeMount, onBeforeUnmount, getCurrentInstance, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showSuccessToast, showConfirmDialog, showImagePreview, showToast } from 'vant';
import { baseURL } from '@/utils/request'
const { proxy } = getCurrentInstance();
const { scenic_label_type, refund_reason, pay_type } = proxy.useDict("scenic_label_type", "refund_reason", "pay_type");
const router = useRouter();
const type = ref('')

// import pic1 from "@/assets/order/pic1.png";

const route = useRoute()

const targetDate = ref(); //目标日期
const timeRemaining = ref();
const currentTime = ref(new Date().getTime());
let timer = -1;
const item = ref();
// const minutes = ref();
// const seconds = ref();
const queryparams = ref({
  refundReason: '',
  id: ''
})

const customFieldName = {
  text: 'label',
  value: 'value',
};
const showPicker = ref(false);

// 复制功能
const copy = () => {
  showToast('复制成功')
}
// 全屏显示
const showQrCode = (e) => {
  showImagePreview([e])
}
// 申请退款
const getRefund = () => {
  type.value = '3'
}
const getRefundOrder = (e) => {
  if (!queryparams.value.id) {
    return showToast('请选择退款原因')
  }
  showConfirmDialog({
    title: '申请退款',
    message:
      '退款申请一旦提交，将不可撤销，是否确认继续退款？',
  })
    .then(() => {
      // on confirm
      // 页面变为退款状态页面
      /*
      refundOrder({ orderId: e.id, refundReason: queryparams.value.id }).then(res => {
        if (res.code == 200) {
          showSuccessToast('申请成功')
          getOrderDetail()
        }
      })
      */
    })
    .catch(() => {
      // on cancel
    });
}

// 取消订单
const getcancelOrder = (e) => {
  if (e.status == 0) {
    showConfirmDialog({
      // title: '标题',
      message:
        '确定取消该订单吗？',
    })
      .then(() => {
        cancelOrder({ orderId: e.id }).then(res => {
          if (res.code == 200) {
            showSuccessToast('取消成功')
            getOrderDetail()
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  }
}

// 再来一单
const getagainOrder = (e) => {
  router.push({
    path: '/home/detail?id=' + e.scenicId,
    query: {
      id: e.scenicId
    }
  })
}
//删除订单
const getdeleteOrder = (e) => {
  showConfirmDialog({
    // title: '',
    message:
      '是否确认删除订单？将不可撤销。',
  })
    .then(() => {
      // on confirm
      delOrder(e.id).then(res => {
        if (res.code == 200) {
          showSuccessToast('删除成功')
          router.back()
        }
      })
    })
    .catch(() => {
      // on cancel
    });
}
// 查看订单详情信息的接口
const getOrderDetail = async () => {
  // console.log('执行了几次：');
  let res = await getOrderById(route.query.id)
  // console.log('订单详情', res)
  item.value = res.data
  type.value = res.data.status
  targetDate.value = new Date(res.data.createTime).getTime() + 1800000; //30分钟是1800000
  nextTick(() => {
    clearInterval(timer);
    // 倒计时功能
    timer = setInterval(function () {
      console.log('倒计时');

      currentTime.value = new Date().getTime();
      timeRemaining.value = targetDate.value - currentTime.value;

      if (timeRemaining.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  })
}
onBeforeMount(() => {
  getOrderDetail()
})

const onConfirm = (e: any) => {
  showPicker.value = false;
  console.log('e:', e);
  queryparams.value.refundReason = e.selectedOptions[0].label;
  queryparams.value.id = e.selectedOptions[0].value;
};

const pay = (item: any) => {
  console.log('pay');
  getpreOrder({ id: item.id }).then(res => {
    if (res.code == 200) {
      console.log('res', res);
      console.log('预下单接口:', res.data);
      router.push({
        path: '/orderPay',
        query: { ...res.data }
      })

    }
  })
  // router.push({
  //   path: '/orderPay',
  //   query: {
  //     id: item.id
  //   }
  // })
}

onBeforeUnmount(() => {
  clearInterval(timer)
})

// 倒计时功能
const minutes = computed(() => {
  if (timeRemaining.value === undefined) {
    return 0;
  }
  return Math.floor((timeRemaining.value % (1000 * 60 * 60)) / (1000 * 60))
}
);
const seconds = computed(() => {
  if (timeRemaining.value === undefined) {
    return 0;
  }
  return Math.floor((timeRemaining.value % (1000 * 60)) / 1000)
});

</script>


<style lang="scss" scoped>
.order-detail-page {
  width: 100%;
  min-height: calc(100vh - 46px);
  padding-top: 46px;
  background-color: var(--cp-bg);
  display: flex;
  flex-direction: column;
  align-items: center;

  p {
    margin: 0 15px;
  }

  .countdown {
    width: 345px;
    height: 40px;
    margin-top: 15px;
    margin-bottom: 15px;

    & p:nth-child(1) {
      font-weight: 700;

      span {
        color: #cb161d;
      }
    }

    & p:nth-child(2) {
      color: #999;
      font-size: 12px;
    }

    // }
  }

  .refundStatus {
    margin: 15px 0;
    padding-bottom: 15px;
    width: 345px;
    // height: 126px;
    border-radius: 10px;
    background-color: #fff;
    margin-bottom: 15px;

    .refundStatus-title {
      padding: 13px 0;
      font-weight: 700;
      font-size: 14px;
    }

    .schedule {
      margin: 5px auto;
      background-color: var(--cp-bg);
      width: 320px;
      // height: 70px;

      p {
        padding: 7px 12px;
        font-size: 10px;
        color: #999;
      }

      & p:nth-child(1) {
        font-size: 12px;
        font-weight: 500;
        color: #333;
        display: flex;
        justify-content: space-between;

        & span:nth-child(2) {
          color: #cb161d;
        }

        i {
          font-style: normal;
        }
      }
    }
  }

  .orderInfo {
    width: 345px;
    height: 120px;
    margin-top: 15px;
    margin-bottom: 15px;
    border-radius: 10px;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 80px;
      height: 80px;
      border-radius: 4px;
    }

    .orderInfo-content {
      width: 230px;
      height: 80px;
      font-size: 11px;
      padding-left: 10px;

      .price {
        color: #cb161d;
        font-size: 18px;
        font-weight: 700;

        i {
          font-size: 12px;
          font-style: normal;
        }
      }
    }

  }

  .orderInfoCard {
    width: 345px;
    // height: 275px;
    background-color: #fff;
    border-radius: 10px;

    i {
      font-style: normal;
    }

    p {
      padding: 10px 0;
      text-align: center;
      display: flex;
      justify-content: space-between;
    }

    .quick {
      .quickTitle {
        text-align: left;
        font-weight: 600;
      }

      img {
        display: block;
        width: 200px;
        height: 200px;
        margin: auto
      }

      .ticketCode {
        margin-top: 5px;
        display: flex;
        align-items: baseline;
        justify-content: center;

        & span:nth-child(1) {
          padding-right: 5px;
        }

        & span:nth-child(2) {
          padding-left: 5px;
        }
      }

      .orderTime {
        border-top: 1px solid #ddd;

        // background-color: #ddd;
        p {
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }

  .requestRefund {
    overflow: hidden;
    width: 345px;
    background-color: #fff;
    margin-top: 15px;
    border-radius: 10px;

    & p:nth-child(1) {
      margin: 0;
    }

    & p:nth-child(2) {
      display: flex;
      justify-content: space-between;
    }

    & p:nth-child(3) {
      color: #999;
      margin-bottom: 20px;
    }

    & p:nth-child(4) {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px
    }
  }

  .refundDetail {
    width: 345px;
    background-color: #fff;
    border-radius: 10px;
    margin: 15px 0;
    padding-bottom: 10px;

    p {
      padding-top: 10px;
      display: flex;
      justify-content: space-between;
    }
  }

  .order-detail-foot {
    position: sticky;
    bottom: 0;
    width: 100%;
    height: 60px;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .footInfo {
      width: 110px;
      font-size: 10px;
      color: rgba(166, 166, 166, 1);

      i {
        font-style: normal;
        color: rgba(198, 20, 27, 1);
        font-size: 12px;
      }

      .price {
        font-size: 18px;
        color: rgba(198, 20, 27, 1);
        font-weight: 700;
      }

      .firstPrice {
        text-decoration: line-through;
        font-size: 14px;

        i {
          color: rgba(166, 166, 166, 1);
        }
      }

      .greybtn {
        display: block;
        width: 120px;
        height: 44px;
        line-height: 44px;
        font-size: 16px;
        color: #333;
        border-radius: 22px;
        border: 1px solid #333;
        text-align: center;
      }
    }

    .confirmbtn {
      display: block;
      width: 225px;
      height: 44px;
      font-size: 16px;
      line-height: 44px;
      color: #fff;
      border-radius: 22px;
      background-color: rgba(198, 20, 27, 1);
      text-align: center;
    }
  }
}

:deep(placeholder) {
  color: red;
  text-align: right;
}
</style>
